package com.example.springcloudgateway.filter;

import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
public class SufFilter extends ZuulFilter {
    Logger log = LoggerFactory.getLogger(SufFilter.class);

    public SufFilter() {
        super();
    }

    @Override
    public String filterType() {
        return "post";
    }

    @Override
    public int filterOrder() {
        return 0;
    }

    @Override
    public boolean shouldFilter() {
        return true;
    }

    @Override
    public Object run() {
        log.info("post....");
        RequestContext ctx = RequestContext.getCurrentContext();
        long total = System.currentTimeMillis() - (long) ctx.get("start");
        log.info("the request use:total=" + total + "ms");
//        ctx.addZuulResponseHeader(); 增加反应的头
        // 1.从head中获取traceId
        HttpServletRequest httpRequest = ctx.getRequest();
        String traceId = httpRequest.getHeader("TRANCE_ID_KEY");

        // 2.添加traceId到response中
        if (!StringUtils.isEmpty(traceId)) {
            HttpServletResponse response = ctx.getResponse();
            response.addHeader("TRANCE_ID_KEY", traceId);
            log.info("response traceId : {}", traceId);
        }
        return null;
    }
}
